;$(function () {

    layui.use(['form', 'laydate', 'table', 'element'], function () {
        var table = layui.table,
            form = layui.form,
            laydate = layui.laydate,
            element = layui.element;
        let nowDate = getNowAndFormatDate();
        let now = {};
        now[nowDate] = "今天";
        let weekDate = getWeekAndFormatDate();
        let showDate = weekDate + " 00:00:00 - " + nowDate + " 23:59:59";
        laydate.render({
            elem: '#reduceOrderDate'
            , range: true
            , trigger: 'click'
            , type: 'datetime'
            , mark: now
            , value: showDate
            , done: function (value, date, endDate) {
                $('#reduceOrderDate').val(value);
                $("#reduceOrderSearchBtn").click();
            }
        });

        $(".layui-btn.layui-btn-primary.dateChoose").on('click', function () {
            let event = $(this).attr("lay-event");
            let nowDate = getNowAndFormatDate();
            switch (event) {
                case 'today':
                    $("#reduceOrderDate").val(nowDate + " 00:00:00 - " + nowDate + " 23:59:59");
                    break;
                case 'yesterday':
                    let yesterday = getYesterdayAndFormatDate();
                    $("#reduceOrderDate").val(yesterday + " 00:00:00 - " + yesterday + " 23:59:59");
                    break;
                case 'lastWeek':
                    let lastWeek = getWeekAndFormatDate();
                    $("#reduceOrderDate").val(lastWeek + " 00:00:00 - " + nowDate + " 23:59:59");
                    break;
                case 'lastMonth':
                    let lastMonth = getMouthAndFormatDate();
                    $("#reduceOrderDate").val(lastMonth + " 00:00:00 - " + nowDate + " 23:59:59");
                    break;
                case 'lastYear':
                    let lastYear = getYearAndFormatDate();
                    $("#reduceOrderDate").val(lastYear + " 00:00:00 - " + nowDate + " 23:59:59");
                    break;
            }
            $("#reduceOrderSearchBtn").click();
            form.render();
        });

        $("#reduceOrderSearchBtn").on('click', function () {
            form.render();
            let searchDate = $("#reduceOrderDate").val();
            let searchOrderId = $("#reduceOrderSearchByOrderId").val();
            table.reload('reduceOrderRender', {
                where: {
                    searchDate: searchDate
                    , searchOrderId: searchOrderId
                },
                page: {
                    curr: 1 //重新从第 1 页开始
                }
            });
        });

        table.render({
            elem: '#reduceOrderTable',
            url: 'getReduceOrder',
            method: "post",
            response: {
                statusCode: true
            },
            where: {
                searchDate: $("#reduceOrderDate").val(),
                searchOrderId: $("#reduceOrderSearchByOrderId").val()
            },
            defaultToolbar: [],
            cellMinWidth: 80,
            cols: [[
                {field: 'sorts', title: '序号', templet: '#sort', width: 58, align: 'center'}
                , {field: 'createDate', title: '下单时间', align: 'center', width: 199}
                , {field: 'orderId', title: '订单号', align: 'center', width: 200}
                , {field: 'waresNum', title: '商品种数', align: 'center'}
                , {field: 'creator', title: '创建人', align: 'center'}
                , {
                    field: 'amount', title: '订单总金额(元)', align: 'center', templet: function (d) {
                        return d.amount.toFixed(2);
                    }
                }
                , {
                    field: 'tool', title: '操作', align: 'center', width: 120,
                    templet: function (d) {
                        return '<span style="text-decoration:underline;cursor:pointer;color:#4BB2FF" lay-event="details">详情</span>'
                    }
                }
            ]],
            id: 'reduceOrderRender',
            page: true
        });
        table.on('tool(reduceOrderTable)', function (obj) {
            let data = obj.data;
            if (obj.event === "details") {
                window.location.href = "toReduceOrderDetails?orderId=" + data.id;
            }
        });

        $("#reduceOrderCreate").on('click', function () {
            window.location.href = "toInsertReduceOrder";
        });
        $("#reduceWaresIdOrNameBtn").on('click', function () {
            table.reload('reduceOrderAddWaresRender', {
                where: {
                    id: $("#reduceWaresIdOrNameVal").val()
                },
                page: {
                    curr: 1 //重新从第 1 页开始
                }
            });
        });
        table.render({
            elem: '#reduceOrderAddWaresTable'
            , url: 'getAllWares'
            , method: "post"
            , response: {
                statusCode: true
            }
            , where: {
                id: $("#reduceWaresIdOrNameVal").val()
            }
            , defaultToolbar: []
            , cellMinWidth: 80
            , cols: [[
                {field: 'id', title: '条码', align: 'center', width: 99}
                , {field: 'name', title: '商品名称', align: 'center'}
                , {field: 'unit', title: '计量单位', align: 'center'}
                , {field: 'category', title: '商品分类', align: 'center', width: 150}
                // , {field: 'freshDate', title: '保鲜期(天)', align: 'center'}
                // , {field: 'expiryDate', title: '保质期(天)', align: 'center'}
                , {
                    field: 'purchase', title: '进价(元)', align: 'center', templet: function (d) {
                        return d.purchase.toFixed(2);
                    }
                }
                , {
                    field: 'price', title: '售价(元)', align: 'center', templet: function (d) {
                        return d.price.toFixed(2);
                    }
                }
                , {field: 'inventory', title: '库存', align: 'center'}
                , {
                    field: 'tool', title: '操作', align: 'center', width: 80,
                    templet: function (d) {
                        return '<span style="text-decoration:underline;cursor:pointer;color:#4BB2FF" lay-event="add">加入</span>'
                    }
                }
            ]],
            id: 'reduceOrderAddWaresRender',
            page: true
        });
        table.on('tool(reduceOrderAddWaresTable)', function (obj) {
            let data = obj.data;
            if (obj.event === "add") {
                let flag = true;
                let oldData = table.cache["reduceOrderAddRender"];
                if (oldData.length !== 0) {
                    $(oldData).each(function (k, v) {
                        $(v.waresId).each(function () {
                            if (this == data.id) {//不改为===
                                layer.msg('添加失败，商品已存在。', {
                                    time: 2000
                                });
                                flag = false;
                            }
                        });
                    });
                }
                if (flag) {
                    // let oldData = table.cache["reduceOrderAddRender"];
                    let datas = {
                        "waresId": data.id
                        , "waresName": data.name
                        , "orderNumber": ''
                        , "unit": data.unit
                        , "category": data.category
                        , "unitPrice": data.purchase.toFixed(2)
                    };
                    oldData.push(datas);
                    table.reload('reduceOrderAddRender', {
                        data: oldData
                    });
                }
            }
        });

        table.render({
            elem: '#reduceOrderAddTable'
            // , url: ''
            , method: "post"
            , response: {
                statusCode: true
            }
            , defaultToolbar: []
            , cellMinWidth: 80
            , data: []
            , cols: [[
                {field: 'waresId', title: '条码', align: 'center', width: 100}
                , {field: 'waresName', title: '商品名称', align: 'center'}
                , {field: 'unit', title: '计量单位', align: 'center'}
                , {field: 'category', title: '商品分类', align: 'center', width: 150}
                , {field: 'unitPrice', title: '退货单价(元)', align: 'center', edit: 'text'}
                , {field: 'orderNumber', title: '退货数量', align: 'center', edit: 'text'}
                , {
                    field: 'tool', title: '操作', align: 'center', width: 80,
                    templet: function (d) {
                        return '<span style="text-decoration:underline;cursor:pointer;color:#FF5722" lay-event="delTableTr">删除</span>'
                    }
                }
            ]],
            id: 'reduceOrderAddRender',
            page: true
        });
        table.on('tool(reduceOrderAddTable)', function (obj) {
            let data = obj.data;
            if (obj.event === "delTableTr") {
                layer.confirm("你确定要删除么？", function (index) {
                        let oldData = table.cache["reduceOrderAddRender"];
                        oldData.splice(obj.tr.data('index'), 1);
                        layer.msg("删除成功", {time: 1000}, function () {
                            table.reload('reduceOrderAddRender', {data: oldData});
                        });
                    }
                );
            }
        });
        table.on('edit(reduceOrderAddTable)', function (obj) {
            let regu = /(^\d+$)|(^\d+\.\d+$)/;
            let data = obj.data
                , value = obj.value
                , field = obj.field;
            if (field === "orderNumber" && !regu.test(value)) {
                layer.msg('退货数量只能为正数。', {
                    time: 2000
                });
                data[field] = "";
                obj.update(data);//更新缓存
                $(this).val("");//更新显示
            } else if (field === "unitPrice") {
                if (!regu.test(value)) {
                    layer.msg('金额格式错误。', {
                        time: 2000
                    });
                    data[field] = "";
                    obj.update(data);//更新缓存
                    $(this).val("");
                } else {
                    let arr = value.split('.');
                    if (arr.length > 1) {
                        arr[1] = arr[1] + '00';
                    }
                    value = arr[0] + '.' + (arr[1] || '00').substring(0, 2);
                    data[field] = value;
                    obj.update(data);//更新缓存
                    $(this).val(value);
                }
            }
        });

        table.render({
            elem: '#reduceOrderDetailsTable'
            , url: 'getOrderWaresByOrderId'
            , method: "post"
            , response: {
                statusCode: true
            },
            where: {
                id: $("#reduceOrderDetailsId").val(),
            }
            , defaultToolbar: []
            , cellMinWidth: 80
            , cols: [[
                {field: 'sorts', title: '序号', width: 58, templet: '#sort', align: 'center'}
                , {field: 'waresId', title: '商品条码', align: 'center', width: 100}
                , {field: 'waresName', title: '商品名称', align: 'center'}
                , {field: 'category', title: '商品分类', align: 'center', width: 150}
                , {field: 'unit', title: '计量单位', align: 'center', width: 90}
                , {field: 'orderNumber', title: '退货数量', align: 'center'}
                , {
                    field: 'unitPrice', title: '退货单价(元)', align: 'center', templet: function (d) {
                        return d.unitPrice.toFixed(2);
                    }
                }
            ]],
            id: 'reduceOrderDetailsRender',
            page: true
        });

        //返回上一页
        $(".reduceOrderTableBack").on('click', function () {
            window.location.href = "toReduceOrder";
        });
        //    保存出库
        $("#reduceOrderTableSave").on('click', function () {
            let tableData = table.cache["reduceOrderAddRender"];
            let dataArray = [];
            if (tableData.length !== 0) {
                $(tableData).each(function (k, v) {
                    delete (this["LAY_TABLE_INDEX"]);
                    dataArray.push(this)
                });
                let flag = true;
                $(dataArray).each(function () {
                    for (let key in this) {
                        if (this[key] === '') {
                            layer.msg('表格数据不能为空。', {
                                time: 2000
                            });
                            flag = false;
                            return false;
                            // break;
                        }
                    }
                });
                if (flag) {
                    $.ajax({
                        url: 'insertReduceOrder',
                        type: "post",
                        dataType: "json",
                        contentType: 'application/json',
                        data: JSON.stringify(dataArray),
                        async: false,
                        success: function (result) {
                            if (result.code === true) {
                                window.location.href = "toReduceOrder";
                            } else {
                                layer.msg(result.msg);
                            }
                        },
                    });
                }
            } else {
                layer.msg('没有可保存的数据。', {
                    time: 2000
                });
            }
        });


    });
});